import db from '../mod/db'
import Log from '../mod/log'

Log.init({data: {platform: 'web'}})
let log = new Log('test-db')

let name = 'local'
let tables = {
  foo: {
    name: 'foo',
  },

  bar: {
    name: 'bar',
    remove: true,
    key: 'id',
  },

  oops: {
    name: 'oops',
    refresh: true,
    key: 'rd',
    indexes: [
      {
        name: 'name',
        unique: false
      },
      {
        name: 'b',
      },
      {
        name: 'mobile',
        unique: true
      }
    ]
  },

}

let data = [
  {rd: 1, name: 'a', b: 1, mobile: 'm1'},
  {rd: 2, name: 'a', b: 0, mobile: 'm2'},
  {rd: 3, name: 'b', b: 1, mobile: 'm4'},
  {rd: 4, name: 'c', b: 0, mobile: 'm6'},
  {rd: 44, name: 'c', b: 0, mobile: 'm7'},
]

let newData = [
  {rd: 10, a: 1, mobile: 'm10'},
  {rd: 11, a: 10, mobile: 'm11'},
]

let test = {
  case: _ => {
    db.open(name, tables, 1)
    // db.open(name)

    .then(e => db.add(e, 'foo', [{ts: new Date().getTime()}]))
    .then(e => db.get(e, 'foo', 2))

    .then(e => db.add(e, tables.oops.name, data))
    .then(e => db.delete(e, tables.oops.name, 1))
    .then(e => db.set(e, tables.oops.name, newData[0].rd, newData[0]))
    .then(e => db.get(e, tables.oops.name, newData[0].rd))
    .then(e => db.getByIndex(e, tables.oops.name, 'name', 'c'))
    .then(e => db.listByIndex(e, tables.oops.name, 'mobile'))
    .then(e => db.deleteByIndex(e, tables.oops.name, 'name', (v) => {
      let b = false
      if (null != v && 'c' == v.name) {
        b = true;
      }
      return b
    }))

    .then(e => db.update(e, tables.oops.name, newData[0].rd, (v) => {
      if (null != v) {
        v.a += 1
      } else {
        v = newData[0]
      }

      return v
    }))
    .then(e => db.updateBatch(e, tables.oops.name,
        newData[0].rd, newData, (old, v) => {
          if (null != old) {
            v.a += old.a
          }

          return v
        }))

    .then(e => db.list(e, tables.oops.name))
    .then(e => db.listByIndex(e, tables.oops.name, 'name', 'c'))
    .then(e => db.listByIndex(e, tables.oops.name, 'name', null, 'b'))
    .then(e => db.listByIndex(e, tables.oops.name, 'name', 'b', 'c'))
    .then(db.close)

    .catch(e => log.w(e))
  }
}

export default test

